package com.zjnx.train.tcp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

public class SocketServer {
	private static Logger logger = LoggerFactory.getLogger(SocketServer.class);
	public static List<SocketClient> socketClientList = new ArrayList<SocketClient>();
	private static Timer timer = new Timer();

	public static void rerfresh() {
		timer.schedule(new SocketClientRefreshTask(), 1000 * 0, 1000 * 30);
	}

	public static void destroyedTimer() {
		if (timer != null) {
			timer.cancel();
		}
	}

	public static void invoke(final Socket client) throws IOException {
		new Thread(new Runnable() {
			public void run() {
				String errcmd = "{\"cmd\":-1}";
				String nocmd = "{\"cmd\":0}";

				BufferedReader in = null;
				PrintWriter out = null;
				try {
					in = new BufferedReader(new InputStreamReader(client.getInputStream()));
					out = new PrintWriter(client.getOutputStream());
					Integer count = 0;
					while (true) {
						String cmdmsg = in.readLine();
						count++;
						logger.debug("count: {}", count);
						logger.debug("Server received {}", cmdmsg);

						JSONObject jsmsg = JSONObject.fromObject(cmdmsg);
						logger.debug("JSONObject success");

						String cmd = jsmsg.getString("cmd");
						if ("1".equals(cmd)) {
							Cmd1Processer.instance.process(client, jsmsg);
							break;
						} else if ("2".equals(cmd)) {
							Cmd2Processer.instance.process(client, jsmsg);
							break;
						} else {
							out.println(nocmd);
							out.flush();

							if ("bye".equals(cmdmsg)) {
								break;
							}
						}
					}
				} catch (JSONException ex) {
					logger.info("JSONObject err");
					out.println(errcmd);
					out.flush();
				} catch (Exception ex) {
					ex.printStackTrace();
				} finally {
					try {
						in.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
					try {
						out.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
					try {
						client.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	static class SocketClientRefreshTask extends java.util.TimerTask {
		public void run() {
			refreshClient();
		}
	}

	private static void refreshClient() {
		List<SocketClient> dels = new ArrayList<SocketClient>();
		for (int i = 0; i < SocketServer.socketClientList.size(); i++) {
			if (SocketServer.socketClientList.get(i).getSocket().isClosed()) {
				dels.add(socketClientList.get(i));
			}
		}
		logger.trace("socket client alive num: " + socketClientList.size());
		logger.trace("dels num:" + dels.size());
		socketClientList.removeAll(dels);
		logger.trace("socket client alive num:" + socketClientList.size());
	}
}
